/*
 * @(#)World.java     14/08/02
 * 
 * Author             Rick Wilson
 * Copyright (c) 2014 Rick Wilson
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of 'Taareekah' nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */



package world;

//~--- non-JDK imports --------------------------------------------------------

import com.jme3.asset.AssetManager;
import com.jme3.asset.plugins.FileLocator;
import com.jme3.export.binary.BinaryExporter;
import com.jme3.material.Material;

import core.Main;

import gameobject.GOManager;

import worldgeneration.WorldGenerator;

//~--- JDK imports ------------------------------------------------------------

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.JMException;

/**
 *
 * @author rick
 */
public class World implements Serializable {

    // Either points to a zip file or the root of the world folder

    /** Field description */
    private File	root	= null;

    /** Field description */
    private File	terrain_root	= null;

    /** Field description */
    private boolean	is_initialized	= false;

    /** Field description */
    private String	world_name;

    /** Field description */
    private int	world_size;

    /** Field description */
    private File	save_root;

    /** Field description */
    private Terrain	terrain;

    /** Field description */
    private GOManager	object_manager;

    /**
     *
     * @param save_root
     */
    public World(File save_root) {
	this.save_root	= save_root;
	object_manager	= new GOManager();
    }

    /**
     *
     * @param filename
     * @param assets
     * @return
     * @throws Exception
     */
    public static World deserializeFromFile(String filename, AssetManager assets) throws Exception {
	try {
	    World			world;
	    FileInputStream		file_in	= new FileInputStream(filename);
	    CustomObjectInputStream	in	= new CustomObjectInputStream(file_in);

	    world	= (World) in.readObject();
	    in.close();
	    file_in.close();
	    world.loadJMEMapMaterials(assets);

	    return world;
	} catch (Exception e) {
	    Logger.getLogger(World.class.getName()).log(Level.SEVERE, "Couldnt load world {0}", e);

	    throw e;
	}
    }

    /**
     *
     * @return
     */
    public GOManager getGOManager() {
	return object_manager;
    }

    /**
     *
     * @return
     */
    public Terrain getTerrain() {
	return terrain;
    }

    /**
     *
     * @return
     */
    public int getWorldSize() {
	return world_size;
    }

    /**
     *
     * @return
     */
    public boolean isInitialized() {
	return is_initialized;
    }

    /**
     * Method description
     *
     *
     * @return
     */
    private boolean saveGenerationParams() {
	return true;
    }

    /**
     * Method description
     *
     *
     * @return
     *
     * @throws Exception
     */
    private boolean createRootDirectoryLayout() throws Exception {

	// Create save root directory if it doesnt exist
	if (!save_root.exists()) {
	    if (!save_root.mkdir()) {
		Logger.getLogger(World.class.getName()).log(Level.SEVERE, "Couldnt create directory {0}",
				 save_root.toString());

		throw new JMException("Couldn't create directory");
	    }
	}

	// Try to create the root directory in save_root
	if (root == null) {
	    root	= new File(save_root, world_name + File.separator);
	}

	// Try to create terrain/ in root directory
	if (terrain_root == null) {
	    terrain_root	= new File(root, "terrain" + File.separator);
	}

	if (root.exists() && root.isDirectory() && terrain_root.exists() && terrain_root.isDirectory()) {
	    return true;
	}

	if (!root.mkdir()) {
	    Logger.getLogger(World.class.getName()).log(Level.SEVERE, "Couldnt create directory {0}", root.toString());

	    throw new JMException("Couldn't create directory");
	}

	if (!terrain_root.mkdir()) {
	    Logger.getLogger(World.class.getName()).log(Level.SEVERE, "Couldnt create directory {0}",
			     terrain_root.toString());

	    throw new JMException("Couldn't create directory");
	}

	return true;
    }

    /**
     * Method description
     *
     *
     * @param assets
     *
     * @return
     *
     * @throws Exception
     */
    private boolean loadJMEMapMaterials(AssetManager assets) throws Exception {
	String	dir	= terrain_root.getPath();

	assets.registerLocator(dir, FileLocator.class);

	for (Map.Entry<String, GenericTerrainMap> entry : terrain.getTerrainMaps().entrySet()) {
	    Material	mat	= (Material) assets.loadMaterial(entry.getKey() + ".j3o");

	    entry.getValue().setMaterial(mat);
	}

	Material	mat	= (Material) assets.loadMaterial("biomes.j3o");

	terrain.getBiomeMap().setMaterial(mat);

	return true;
    }

    /**
     * Method description
     *
     *
     * @return
     *
     * @throws Exception
     */
    private boolean saveJMEMapMaterials() throws Exception {
	BinaryExporter	exporter	= BinaryExporter.getInstance();

	for (Map.Entry<String, GenericTerrainMap> entry : terrain.getTerrainMaps().entrySet()) {
	    Material	mat	= entry.getValue().getMaterial();

	    if (mat == null) {
		continue;
	    }

	    File	file	= new File(terrain_root, entry.getKey() + ".j3o");

	    exporter.save(mat, file);
	}

	Material	mat	= terrain.getBiomeMap().getMaterial();

	if (mat == null) {
	    return false;
	}

	File	file	= new File(terrain_root, "biomes.j3o");

	exporter.save(mat, file);

	return true;
    }

    /**
     * Method description
     *
     *
     * @return
     *
     * @throws Exception
     */
    private boolean saveTerrainMaps() throws Exception {
	if (!terrain.saveMapsAsBitmap(terrain_root.toString())) {
	    return false;
	}

	if (!terrain.saveMapsAsRaw(terrain_root.toString())) {
	    return false;
	}

	if (!terrain.saveMapsAsHumanReadable(terrain_root.toString())) {
	    return false;
	}

	saveJMEMapMaterials();

	return true;
    }

    /**
     *
     * @param new_world_name
     * @return
     * @throws Exception
     */
    public boolean save(String new_world_name) throws Exception {
	world_name	= new_world_name;
	root		= null;
	terrain_root	= null;
	createRootDirectoryLayout();
	saveTerrainMaps();
	saveGenerationParams();
	serializeToFile(root.toString() + File.separator + "world.ser");

	return true;
    }

    /**
     *
     * @return
     * @throws Exception
     */
    public boolean save() throws Exception {
	createRootDirectoryLayout();
	saveTerrainMaps();
	saveGenerationParams();
	serializeToFile(root.toString() + File.separator + "world.ser");

	return true;
    }

    /**
     *
     * @param filename
     * @return
     * @throws Exception
     */
    public boolean serializeToFile(String filename) throws Exception {
	FileOutputStream	file_out	= new FileOutputStream(filename);
	ObjectOutputStream	out		= new ObjectOutputStream(file_out);

	out.writeObject(this);
	out.close();
	file_out.close();
	Logger.getLogger(World.class.getName()).log(Level.INFO, "Serialized to file");

	return true;
    }

    /**
     *
     * @throws Exception
     */
    public void reset() throws Exception {
	object_manager	= null;
	object_manager	= new GOManager();
	terrain		= null;
	world_name	= "";
	world_size	= -1;

	// Either points to a zip file or the root of the world folder
	root		= null;
	terrain_root	= null;
	is_initialized	= false;
    }

    /**
     *
     * @param generator
     * @return
     * @throws Exception
     */
    public final boolean initFromWorldGenerator(WorldGenerator generator) throws Exception {
	if (generator.isGenerated() == false) {
	    return false;
	}

	world_name	= generator.getWorldName();
	world_size	= generator.getWorldSize();
	terrain		= null;
	terrain		= generator.getTerrain();
	createRootDirectoryLayout();
	is_initialized	= true;

	return true;
    }

    /**
     *
     * @param terrain
     */
    public void setTerrain(Terrain terrain) {
	this.terrain	= terrain;
    }

    /**
     * Used for serialization.
     */
    protected static class CustomObjectInputStream extends ObjectInputStream {

	/**
	 *
	 * @param in
	 * @throws IOException
	 */
	public CustomObjectInputStream(InputStream in) throws IOException {
	    super(in);
	}

	/**
	 * Method description
	 *
	 *
	 * @param desc
	 *
	 * @return
	 *
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	@Override
	protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
	    try {
		return super.resolveClass(desc);
	    } catch (ClassNotFoundException e) {
		return Main.getScriptManager().getScriptComponentClass(desc.getName());
	    }
	}
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
